/*+++
 *GuudButton.cpp
 *
 *  Created on: 2013-1-25
 *      Author: heqiu
 */

#include "GuudButton.h"

namespace guud {
GuudButton::GuudButton() {
	m_bShow = true;
	m_bListen = true;
	m_pGuudSurface = NULL;
	m_status = GUUD_BUTTON_STATUS_OUT;
	m_func_pressed = NULL;
}
GuudButton::GuudButton(const GuudButton & obj) {
	m_bShow = true;
	m_bListen = true;
	m_pGuudSurface = obj.m_pGuudSurface;
	m_rectIn = obj.m_rectIn;
	m_rectOut = obj.m_rectOut;
	m_rectPressed = obj.m_rectPressed;
	m_status = GUUD_BUTTON_STATUS_OUT;
	m_sName = obj.m_sName;
	m_func_pressed = NULL;
}
void GuudButton::setFuncPressed(void (*func_pressed)(void *, GuudButton *)) {
	m_func_pressed = func_pressed;
}
void GuudButton::setSurface(GuudSurface * pSurface, GuudRect & rectIn,
		GuudRect & rectOut, GuudRect & rectPressed) {
	m_pGuudSurface = pSurface;
	m_rectIn = rectIn;
	m_rectOut = rectOut;
	m_rectPressed = rectPressed;
}
bool GuudButton::bPointIn(int32_t iX, int32_t iY) {
	bool bRet = false;
	switch (m_status) {
	case GUUD_BUTTON_STATUS_OUT:
		if (m_rectOut.w >= (uint32_t) iX && m_rectOut.h >= (uint32_t) iY) {
			iX += m_rectOut.x;
			iY += m_rectOut.y;
			bRet = m_pGuudSurface->bPointIn(iX, iY);
		}
		break;
	case GUUD_BUTTON_STATUS_IN:
		if (m_rectIn.w >= (uint32_t) iX && m_rectIn.h >= (uint32_t) iY) {
			iX += m_rectIn.x;
			iY += m_rectIn.y;
			bRet = m_pGuudSurface->bPointIn(iX, iY);
		}
		break;
	case GUUD_BUTTON_STATUS_PRESSED:
		if (m_rectPressed.w >= (uint32_t) iX
				&& m_rectPressed.h >= (uint32_t) iY) {
			iX += m_rectPressed.x;
			iY += m_rectPressed.y;
			bRet = m_pGuudSurface->bPointIn(iX, iY);
		}
		break;
	}
	return bRet;
}
void GuudButton::handleEvent(GuudPoint & stPoint, GuudEvent & stEvent,
		void * pData) {
	if (!m_bListen) {
		return;
	}
	if (stEvent.type == SDL_MOUSEMOTION) {
		int32_t iX = stEvent.motion.x - stPoint.m_iX;
		int32_t iY = stEvent.motion.y - stPoint.m_iY;
		if (m_status == GUUD_BUTTON_STATUS_IN
				|| m_status == GUUD_BUTTON_STATUS_OUT) {
			if (bPointIn(iX, iY)) {
				m_status = GUUD_BUTTON_STATUS_IN;
			} else {
				m_status = GUUD_BUTTON_STATUS_OUT;
			}
		} else if (m_status == GUUD_BUTTON_STATUS_PRESSED) {
			if (!bPointIn(iX, iY)) {
				m_status = GUUD_BUTTON_STATUS_OUT;
			}
		}

	} else if (stEvent.type == SDL_MOUSEBUTTONDOWN) {
		int32_t iX = stEvent.motion.x - stPoint.m_iX;
		int32_t iY = stEvent.motion.y - stPoint.m_iY;
		if (bPointIn(iX, iY)) {
			m_status = GUUD_BUTTON_STATUS_PRESSED;
		}
	} else if (stEvent.type == SDL_MOUSEBUTTONUP) {
		if (m_status == GUUD_BUTTON_STATUS_PRESSED) {
			if (m_func_pressed != NULL) {
				m_func_pressed(pData, this);
			}
		}
		int32_t iX = stEvent.motion.x - stPoint.m_iX;
		int32_t iY = stEvent.motion.y - stPoint.m_iY;
		if (bPointIn(iX, iY)) {
			m_status = GUUD_BUTTON_STATUS_IN;
		} else {
			m_status = GUUD_BUTTON_STATUS_OUT;
		}
	}
}
}

